<script setup>
import { DrawEvent, DrawPolygon, DrawRect } from '@antv/l7-draw'
import { ref, inject, onMounted, onUnmounted } from 'vue'
import api from '@/axios/smart_city'
import * as turf from '@turf/turf'
import { PolygonLayer } from '@antv/l7'

let map, scene, draw, events, eventsLayer
const eventsData = ref([])
function initDraw() {
  if(draw) {
    draw.destroy()
    draw = null
  }
  draw = new DrawRect(scene, {})
  draw.on(DrawEvent.Add, (e) => {
    let res = turf.pointsWithinPolygon(events, e)
    draw.destroy()
    eventsData.value = res.features.map((item) => {
      return {
        center: item.geometry.coordinates, 
        ...item.properties,
      }
    })
    if(eventsLayer) {
      scene.removeLayer(eventsLayer)
    }
    eventsLayer = new PolygonLayer({name: "查询事故点"})
      .source(res)
      .shape('circle')
      .active(true)
      .animate(true)
      .size(50)
      .color('red')

    scene.addLayer(eventsLayer)
  })
  draw.enable()
}
const getEvents = async () => { 
  events = await api.getEvents()
}
onMounted(() => {
  ({map, scene} = inject('mapScene'))
  map.flyTo({
    center: [114.3, 30.5],
    zoom: 12,
    speed: 2,
    pitch: 0,
    bearing: 0
  })
  getEvents()
})
onUnmounted(() => {
  if(draw) {
    draw.destroy()
    draw = null
  }
  if(eventsLayer) {
    scene.removeLayer(eventsLayer)
  }
})
</script>

<template>
  <div class="search-container">
    <el-button @click="initDraw" type="primary">拉框査询</el-button>
  </div>
  <div class="displayTable" v-if="eventsData.length">
    <el-table :data="eventsData" border style="width: 100%" :max-height="150" size="small">
      <el-table-column prop="event_num" label="事故编号" width="180" />
      <el-table-column prop="name" label="事故类型" />
      <el-table-column prop="event_num" label="事故等级" />
      <el-table-column prop="area" label="发生区域" />
      <el-table-column prop="car_num" label="车牌号" />
      <el-table-column prop="phone" label="手机号码" />
    </el-table>
  </div>
</template>

<style lang="scss" scoped>
.search-container {
  position: absolute;
  z-index: 9;
  top: 100px;
  left: calc(100vw - 150px);
  width: 150px;
  height: 80px;
  display: flex;
  justify-self: center;
  align-items: center;
}
.displayTable {
  position: absolute;
  z-index: 9;
  left: 80px;
  top: 100px;
}

:deep(.el-table) {
  background-color: transparent;
}

:deep(.el-table tr) {
  background: transparent;
  color: black;
  cursor: pointer;
}

:deep(.el-table tr:hover) {
  background: #333;
}

:deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
  background-color: white;
  opacity: 70%;
}

:deep(.el-table th.el-table__cell) {
  border-bottom: none;
}

:deep(.el-table__inner-wrapper::before) {
  height: 0;
}
</style>
